﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Win32;

namespace MyDefaults.Core
{
    public class MySettings
    {
        public const int MinIntervalMilliseconds = 200;
        public const int MaxIntervalMilliseconds = 5000;

        private int _updateIntervalMilliseconds = 500; // default
        private readonly IList<RegistryEntry> _registryEntries = new List<RegistryEntry>();

        public void Update()
        {
            _registryEntries.Clear();

            XmlElement configElement = System.Configuration.ConfigurationManager.GetSection("myDefaults") as XmlElement;
            
            if (configElement != null)
            {
                try
                {
                    if (configElement.Attributes["updateIntervalMilliseconds"] != null)
                    {
                        int intervalMilliseconds = int.Parse(configElement.Attributes["updateIntervalMilliseconds"].Value);

                        if (intervalMilliseconds >= MinIntervalMilliseconds &&
                            intervalMilliseconds <= MaxIntervalMilliseconds)
                        {
                            _updateIntervalMilliseconds = intervalMilliseconds;
                        }
                    }
                }
                catch (FormatException) { }

                for (int i = 0; i < configElement.ChildNodes.Count; i++)
                {
                    XmlNode node = configElement.ChildNodes[i];

                    if (node.Name == "regEntry")
                    {
                        string description = node.Attributes["desc"].Value;
                        string keyName = node.Attributes["keyName"].Value;
                        string valueName = node.Attributes["valueName"].Value;
                        string valueKindAsString = node.Attributes["valueKind"].Value;
                        string value = node.Attributes["value"].Value;

                        RegistryValueKind valueKind = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), valueKindAsString);

                        _registryEntries.Add(new RegistryEntry(description, keyName, valueName, valueKind, value));
                    }
                }
            }
        }

        public int UpdateInterval { get { return _updateIntervalMilliseconds; } }

        public IList<RegistryEntry> RegistryEntries
        {
            get { return _registryEntries; }
        }
    }
}
